<template>
  <div class="app-container">
    <!-- 搜索头部 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="单据编码" prop="buyBackOrderCode">
        <el-input
          v-model="queryParams.buyBackOrderCode"
          placeholder="请输入采购退货编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId">
        <el-select
          v-model="queryParams.supplierId"
          clearable
          placeholder="请选择供应商"
        >
          <el-option
            :label="supplier.supName"
            :value="supplier.id"
            v-for="supplier in supplierList"
            :key="supplier.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="单据日期">
        <el-date-picker
          v-model="daterangeDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="单据阶段" prop="orderStatus">
        <el-select
          v-model="queryParams.orderStatus"
          clearable
          placeholder="请选择"
        >
          <el-option
            :label="orderStatus.name"
            :value="orderStatus.id"
            v-for="orderStatus in orderStatusList"
            :key="orderStatus.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审批结果" prop="approvalResult">
        <el-select
          v-model="queryParams.approvalResult"
          clearable
          placeholder="请选择"
        >
          <el-option
            :label="approval.name"
            :value="approval.id"
            v-for="approval in approvalList"
            :key="approval.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="已生效" prop="isEffect">
        <el-select
          v-model="queryParams.isEffect"
          clearable
          placeholder="请选择"
        >
          <el-option
            :label="isEffect.name"
            :value="isEffect.id"
            v-for="isEffect in isEffectList"
            :key="isEffect.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="生效时间">
        <el-date-picker
          v-model="daterangeEffectDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="修改时间">
        <el-date-picker
          v-model="daterangeModifyDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 中部按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['caigou:buyBackOrder:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['caigou:buyBackOrder:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <!-- 中部数据表格 -->
    <el-table
      v-loading="loading"
      :data="buyBackOrderList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column fixed="left" label="序号" width="70" align="center">
        <template slot-scope="scope">
          {{
            scope.$index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="采购退货编码"
        fixed="left"
        align="center"
        prop="buyBackOrderCode"
        width="200"
      >
        <template slot-scope="scope">
          <el-link type="primary" @click="showBuyBackOrder(scope.row)">
            {{ scope.row.buyBackOrderCode }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column
        label="采购退货申请单"
        fixed="left"
        align="center"
        prop="buyBackReq.code"
        width="200"
      >
        <template slot-scope="scope">
          {{ scope.row.buyBackReq.code }}
        </template>
      </el-table-column>
      <el-table-column
        label="供应商"
        align="center"
        prop="supName"
        width="150"
      />
      <el-table-column
        label="应出库数量"
        align="center"
        prop="allOutStock"
        width="150"
      />
      <el-table-column
        label="实际出库数量"
        align="center"
        prop="realOutStock"
        width="150"
      />
      <el-table-column
        label="应收款"
        align="center"
        prop="allInPrice"
        width="150"
      />
      <el-table-column
        label="实际收款"
        align="center"
        prop="realInPrice"
        width="150"
      />
      <el-table-column label="出库状态" align="center" prop="stockStatusName">
      </el-table-column>
      <el-table-column label="收款状态" align="center" prop="payStatusName">
      </el-table-column>
      <el-table-column
        label="单据日期"
        align="center"
        prop="orderDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="业务部门" align="center" prop="srcDeptName" />
      <el-table-column label="业务员" align="center" prop="srcUserName" />
      <el-table-column label="单据阶段" align="center" prop="orderStatusName">
      </el-table-column>
      <el-table-column
        label="审核人"
        align="center"
        prop="approvalUser.userName"
      />
      <el-table-column
        label="审批结果"
        align="center"
        prop="approvalResultName"
      >
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.approvalResult == 2">{{
            scope.row.approvalResultName
          }}</el-tag>
          <el-tag type="danger" v-if="scope.row.approvalResult == 3">{{
            scope.row.approvalResultName
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否生效" align="center" prop="isEffectName">
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="生效时间"
        align="center"
        prop="effectDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.effectDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="modifyBy" />
      <el-table-column
        label="修改时间"
        align="center"
        prop="modifyDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.modifyDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        align="center"
        class-name="small-padding fixed-width"
        width="120"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['caigou:buyBackOrder:edit']"
            :disabled="scope.row.orderStatus != 2"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            :disabled="scope.row.approvalResult != 3"
            v-hasPermi="['caigou:buyBackOrder:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购退货单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :disabled="formDisabled"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="采购退货编码" prop="buyBackOrderCode">
              <el-input
                v-model="form.buyBackOrderCode"
                placeholder="请输入采购退货编码"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="采购退货申请单" prop="buyBackReqId">
              <el-select
                :value="form.buyBackReqId"
                clearable
                placeholder="请选择采购退货申请单"
              >
                <el-option
                  :label="form.buyBackReq.code"
                  :value="form.buyBackReqId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-button @click="showBuyBackReq">采购退货申请单</el-button>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商" prop="supplierId">
              <el-select
                v-model="form.supplierId"
                clearable
                placeholder="请选择供应商"
                @change="resetDetailList"
              >
                <el-option
                  :label="supplier.supName"
                  :value="supplier.id"
                  v-for="supplier in supplierList"
                  :key="supplier.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="单据日期" prop="orderDate">
              <el-date-picker
                clearable
                v-model="form.orderDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择单据日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="源单业务员">
              <el-input
                :value="form.srcUser.userName"
                placeholder=""
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务部门">
              <el-input :value="form.srcDeptName" placeholder="" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <i
          class="el-icon-arrow-down"
          @click="showFormDetail"
          style="cursor: pointer"
        ></i>
        <el-divider></el-divider>
        <div v-show="formDetailDisabled">
          <el-row>
            <el-col :span="8">
              <el-form-item label="出库数量">
                <el-input :value="form.allOutStock" placeholder="" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="实际出库数量">
                <el-input :value="form.realOutStock" placeholder="" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="应收款">
                <el-input :value="form.allInPrice" placeholder="" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="实际收款">
                <el-input :value="form.realInPrice" placeholder="" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="出库状态">
                <el-input
                  :value="form.stockStatusName"
                  placeholder=""
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="收款状态">
                <el-input :value="form.payStatusName" placeholder="" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="审核人" prop="approvalUser.userName">
                <el-input
                  :value="form.approvalUser.userName"
                  disabled
                  placeholder=""
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="审核结果" prop="approvalResultName">
                <el-input
                  :value="form.approvalResultName"
                  disabled
                  placeholder=""
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="审核意见" prop="approvalOption">
                <el-input
                  type="textarea"
                  :value="form.approvalOption"
                  disabled
                  placeholder=""
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="创建人" prop="createBy">
                <el-input :value="form.createBy" placeholder="" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="修改人" prop="modifyBy">
                <el-input :value="form.modifyBy" placeholder="" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="创建时间" prop="createDate">
                <el-date-picker
                  clearable
                  :value="form.createDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  disabled
                  placeholder=""
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="修改时间" prop="modifyDate">
                <el-date-picker
                  clearable
                  :value="form.modifyDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  disabled
                  placeholder=""
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="备注" prop="remark">
                <el-input
                  type="textarea"
                  v-model="form.remark"
                  placeholder=""
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <el-menu
          :default-active="activeIndex"
          class="el-menu-demo"
          mode="horizontal"
          @select="handleDetailSelect"
        >
          <el-menu-item index="1">采购退货申请单明细</el-menu-item>
          <el-menu-item index="2">采购退货明细</el-menu-item>
        </el-menu>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            :disabled="reqSingle"
            @click="handleDetailAdd"
            v-show="activeIndex == '1'"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="orderMultiple"
            @click="handleDetailDelete"
            v-show="activeIndex == '2'"
            >删除</el-button
          >
        </el-col>
        <el-table
          ref="reqTable"
          :data="buyBackReqDetailList"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleReqDetailSelectionChange"
          v-show="activeIndex == '1'"
        >
          <el-table-column
            type="selection"
            :selectable="isRowSelectable"
            width="70"
            align="left"
          />
          <el-table-column label="序号" width="70" align="left">
            <template slot-scope="scope">
              {{
                scope.$index +
                1 +
                (queryParams.pageNum - 1) * queryParams.pageSize
              }}
            </template>
          </el-table-column>
          <el-table-column prop="goods.proName" label="商品" width="150">
          </el-table-column>
          <el-table-column prop="goods.unitName" label="单位" width="120">
          </el-table-column>
          <el-table-column prop="quantity" label="退货数量" width="120">
          </el-table-column>
          <el-table-column prop="cost" label="单价" width="300">
          </el-table-column>
          <el-table-column prop="remark" label="备注" width="120">
          </el-table-column>
        </el-table>
        <el-table
          ref="orderTable"
          :data="form.buyBackOrderDetailList"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleOrderDetailSelectionChange"
          v-show="activeIndex == '2'"
          highlight-current-row
        >
          <el-table-column type="selection" width="70" align="center" />
          <el-table-column label="序号" width="70" align="center">
            <template slot-scope="scope">
              {{
                scope.$index +
                1 +
                (queryParams.pageNum - 1) * queryParams.pageSize
              }}
            </template>
          </el-table-column>
          <el-table-column prop="goods.proName" label="商品" width="150">
          </el-table-column>
          <el-table-column prop="houseId" label="仓库" width="120">
            <template slot-scope="scope">
              <el-form-item prop="houseId" label-width="120">
                <el-select
                  v-model="scope.row.houseId"
                  @change="handleHouseChange(scope.row)"
                >
                  <el-option
                    :label="warehouse.houseName"
                    :value="warehouse.id"
                    v-for="warehouse in warehouseList"
                    :key="warehouse.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="goods.unitName" label="单位" width="120">
          </el-table-column>
          <el-table-column prop="outStock" label="退货数量" width="80">
            <template slot-scope="scope">
              <el-form-item prop="outStock" label-width="100">
                <el-input
                  v-model="scope.row.outStock"
                  :min="0"
                  @blur="validateStock(scope.row)"
                  @input="calculateCostAll(scope.row)"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="cost" label="单价" width="120">
          </el-table-column>
          <el-table-column label="结算金额" width="120">
            <template slot-scope="scope">
              {{ (scope.row.outStock * scope.row.cost).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="申请退货数量" width="120">
          </el-table-column>
          <el-table-column prop="stock" label="库存数量" width="120">
          </el-table-column>
        </el-table>
      </el-form>
      <!-- 采购入库单内部对话框 -->
      <el-dialog
        width="60%"
        title="选择采购退货申请单"
        :visible.sync="innerVisible"
        append-to-body
      >
        <!-- 搜索头部 -->
        <el-form
          :model="queryBuyBackReqParams"
          ref="queryBuyBackReqForm"
          size="small"
          :inline="true"
          v-show="showBuyBackReqSearch"
          label-width="68px"
        >
          <el-form-item label="单据编号" prop="code">
            <el-input
              v-model="queryBuyBackReqParams.code"
              placeholder="请输入单据编号"
              clearable
              @keyup.enter.native="handleBuyBackReqQuery"
            />
          </el-form-item>
          <el-form-item label="单据日期">
            <el-date-picker
              v-model="daterangeBuyBackReqOrderDate"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleBuyBackReqQuery"
              >搜索</el-button
            >
            <el-button
              icon="el-icon-refresh"
              size="mini"
              @click="resetBuyBackReqQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
        <el-table
          ref="buyBackReqTable"
          v-loading="buyBackReqLoading"
          :data="buyBackReqList"
          highlight-current-row
          row-key="id"
          @current-change="handleCurrentChange"
        >
          <el-table-column label="序号" width="70" align="center" fixed>
            <template slot-scope="scope">
              {{
                scope.$index +
                1 +
                (queryBuyBackReqParams.pageNum - 1) *
                  queryBuyBackReqParams.pageSize
              }}
            </template>
          </el-table-column>
          <el-table-column
            fixed
            prop="buyBackReqCode"
            label="单据编号"
            width="150"
          >
            <template slot-scope="scope">
              <el-popover
                placement="top-start"
                width="200"
                trigger="hover"
                :content="scope.row.code"
              >
                <div slot="reference" class="ellipsis-text">
                  {{ scope.row.code }}
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="createDate" label="创建日期" width="120">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createDate, "{y}-{m}-{d}") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="stockIn.stockInCode"
            label="采购入库单"
            width="120"
          >
          </el-table-column>
          <el-table-column prop="supplier.supName" label="供应商" width="120">
          </el-table-column>
          <el-table-column prop="srcDeptName" label="业务部门" width="120">
          </el-table-column>
          <el-table-column prop="srcUser.userName" label="业务员" width="120">
          </el-table-column>
          <el-table-column prop="allOutStock" label="退货数量" width="120">
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <pagination
          v-show="buyBackReqTotal > 0"
          :total="buyBackReqTotal"
          :page.sync="queryBuyBackReqParams.pageNum"
          :limit.sync="queryBuyBackReqParams.pageSize"
          @pagination="getBuyBackReqList"
        />
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formDisabled"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBuyBackOrder,
  getBuyBackOrderById,
  delBuyBackOrder,
  addBuyBackOrder,
  updateBuyBackOrder,
  listAll,
} from "@/api/caigou/buyBackOrder";
import {
  listBuyBackReq,
  getBuyBackReqDetailListByBuyBackReqId,
} from "@/api/caigou/buyBackReq";
import { listAllSupplies } from "@/api/basedata/supplies";
import { listWarehouseInfoAll } from "@/api/store/warehouseInfo";
import { getStockByGoodsIdHouseId } from "@/api/store/warehouseGoods";

export default {
  name: "BuyBackOrder",
  data() {
    return {
      // 选中菜单
      activeIndex: "2",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 采购入库单添加按钮禁用
      reqSingle: true,
      // 采购退货单删除按钮禁用
      orderMultiple: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购退货单表格数据
      buyBackOrderList: [],
      // 中间数组
      tempDetailList: [],
      //仓库列表
      warehouseList: [],
      // 供应商列表
      supplierList: [],
      // 采购列表
      buyBackReqList: [],
      // 审批结果列表
      approvalList: [
        {
          id: 1,
          name: "未审批",
        },
        {
          id: 2,
          name: "已通过",
        },
        {
          id: 3,
          name: "已驳回",
        },
      ],
      // 单据阶段列表
      orderStatusList: [
        {
          id: 2,
          name: "已提交",
        },
        {
          id: 3,
          name: "已审批",
        },
        {
          id: 4,
          name: "执行完",
        },
      ],
      //是否生效
      isEffectList: [
        {
          id: 0,
          name: "未生效",
        },
        {
          id: 1,
          name: "已生效",
        },
      ],
      //是否关闭
      isCloseList: [
        {
          id: 0,
          name: "未关闭",
        },
        {
          id: 1,
          name: "已关闭",
        },
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeDate: [],
      // 备注时间范围
      daterangeEffectDate: [],
      // 备注时间范围
      daterangeCreateDate: [],
      // 备注时间范围
      daterangeModifyDate: [],
      // 明细选中数组
      detailsSelection: [],
      //采购入库单明细列表
      buyBackReqDetailList: [],
      // 采购退货详细信息
      formDetailDisabled: false,
      //内部采购入库单控制
      innerVisible: false,
      // 内部采购入库单搜索参数
      queryBuyBackReqParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        approvalResult: 2,
        isEffect: 1,
        isClose: 0,
        supplierId: null,
      },
      /**
       * 内部采购退货申请单列表
       */
      // 内部采购退货申请单创建时间范围
      daterangeBuyBackReqOrderDate: [],
      // 内部采购退货申请单加载状态
      buyBackReqLoading: false,
      // 内部采购退货申请单总数
      buyBackReqTotal: 0,
      // 内部采购退货申请单查询表单控制
      showBuyBackReqSearch: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        buyBackOrderCode: null,
        supplierId: null,
        buyOrderId: null,
        orderStatus: null,
        buyBackReqId: null,
        stockStatus: null,
        payStatus: null,
        orderDate: null,
        deptId: null,
        userId: null,
        status: null,
        approvalResult: null,
        isEffect: null,
        isClose: null,
        isCancel: null,
        effectDate: null,
        createDate: null,
        modifyDate: null,
      },
      // 表单参数
      form: {
        //采购退货订单详情列表
        buyBackOrderDetailList: [],
        approvalUser: { userName: "" },
        srcUser: { userName: null },
        srcDeptName: null,
        buyBackReq: {
          code: "",
        },
      },
      //表单禁用控制
      formDisabled: false,
      // 表单校验
      rules: {
        buyBackOrderCode: [
          { required: true, message: "采购退货编码不能为空", trigger: "blur" },
        ],
        buyBackReqId: [
          {
            required: true,
            message: "采购退货申请单不能为空",
            trigger: "blur",
          },
        ],
        supplierId: [
          { required: true, message: "供应商id不能为空", trigger: "blur" },
        ],
        allOutStock: [
          { required: true, message: "总出库数量不能为空", trigger: "blur" },
        ],
        allInPrice: [
          { required: true, message: "总收款不能为空", trigger: "blur" },
        ],
        orderDate: [
          { required: true, message: "单据日期不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getSupplierList();
    this.getWarehouseList();
  },
  methods: {
    /**
     * 获取所有仓库信息
     */
    getWarehouseList() {
      listWarehouseInfoAll().then((response) => {
        this.warehouseList = response.data;
      });
    },
    /**
     * 获取供应商列表
     */
    getSupplierList() {
      listAllSupplies().then((response) => {
        this.supplierList = response.data;
      });
    },
    /** 查询采购退货单列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeDate && "" != this.daterangeDate) {
        this.queryParams.params["beginDate"] = this.daterangeDate[0];
        this.queryParams.params["endDate"] = this.daterangeDate[1];
      }
      if (null != this.daterangeEffectDate && "" != this.daterangeEffectDate) {
        this.queryParams.params["beginEffectDate"] =
          this.daterangeEffectDate[0];
        this.queryParams.params["endEffectDate"] = this.daterangeEffectDate[1];
      }
      if (null != this.daterangeCreateDate && "" != this.daterangeCreateDate) {
        this.queryParams.params["beginCreateDate"] =
          this.daterangeCreateDate[0];
        this.queryParams.params["endCreateDate"] = this.daterangeCreateDate[1];
      }
      if (null != this.daterangeModifyDate && "" != this.daterangeModifyDate) {
        this.queryParams.params["beginModifyDate"] =
          this.daterangeModifyDate[0];
        this.queryParams.params["endModifyDate"] = this.daterangeModifyDate[1];
      }
      listBuyBackOrder(this.queryParams).then((response) => {
        this.buyBackOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        buyBackOrderCode: null,
        buyBackReqId: null,
        supplierId: null,
        buyOrderId: null,
        allOutStock: null,
        realOutStock: null,
        allInPrice: null,
        realInPrice: null,
        stockStatus: null,
        payStatus: null,
        orderDate: null,
        deptId: null,
        userId: null,
        status: null,
        approvalResult: null,
        isEffect: null,
        isClose: null,
        isCancel: null,
        remark: null,
        effectDate: null,
        createBy: null,
        createDate: null,
        modifyBy: null,
        modifyDate: null,
        isDel: null,
        buyBackOrderDetailList: [],
        approvalUser: { userName: "" },
        srcUser: { userName: null },
        srcDeptName: null,
        buyBackReq: {
          code: "",
        },
      };
      this.buyBackReqDetailList = [];
      this.tempDetailList = [];
      this.deleteIds = [];
      this.detailsSelection = [];
      this.activeIndex = "2";
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeDate = [];
      this.daterangeEffectDate = [];
      this.daterangeCreateDate = [];
      this.daterangeModifyDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.formDisabled = false;
      this.form.buyBackOrderCode = "CGTH" + Date.now();
      this.open = true;
      this.title = "添加采购退货单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.formDisabled = false;
      this.getBuyBackOrder(row);
      this.open = true;
      this.title = "修改采购退货单";
    },
    //展示采购退货单
    showBuyBackOrder(row) {
      this.reset();
      this.getBuyBackOrder(row);
      this.formDisabled = true;
      this.open = true;
      this.title = "查看采购退货单";
    },
    //获取采购退货单详情
    getBuyBackOrder(row) {
      const id = row.id || this.ids;
      getBuyBackOrderById(id).then((response) => {
        this.form = response.data;
        // this.buyBackReq = this.form.buyBackReq;
        getBuyBackReqDetailListByBuyBackReqId(this.form.buyBackReqId).then(
          (rs) => {
            this.buyBackReqDetailList = rs.data;
            this.form.buyBackOrderDetailList.forEach((buyBackOrderDetail) => {
              this.buyBackReqDetailList.forEach((buyBackReqDetail) => {
                if (buyBackOrderDetail.goodsId === buyBackReqDetail.goodsId) {
                  buyBackOrderDetail.id = buyBackReqDetail.id;
                  const index = this.buyBackReqDetailList.findIndex(
                    (item) => item.id === buyBackReqDetail.id
                  );
                  buyBackOrderDetail.index = index;
                  if (index !== -1) this.setRowDisabled(index, true);
                }
              });
            });
          }
        );
      });
    },
    /** 提交按钮 */
    submitForm() {
      const returnIs = this.checkForm();
      if (!returnIs) {
        return;
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateBuyBackOrder(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBuyBackOrder(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除采购退货单编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBuyBackOrder(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "caigou/buyBackOrder/export",
        {
          ...this.queryParams,
        },
        `buyBackOrder_${new Date().getTime()}.xlsx`
      );
    },
    // 子表单选择器
    handleDetailSelect(key, keyPath) {
      this.activeIndex = key;
    },
    // 采购退货明细多级选择器
    handleOrderDetailSelectionChange(val) {
      this.detailsSelection = val;
      this.orderMultiple = !val.length;

      this.deleteIds = val.map((row) => row.id);
    },
    // 采购入库明细多级选择器
    handleReqDetailSelectionChange(val) {
      this.detailsSelection = val;
      this.reqSingle = !val.length;

      this.tempDetailList = [];
      this.tempDetailList = val.map((row) => {
        const index = this.buyBackReqDetailList.findIndex(
          (item) => item.id === row.id
        );
        return { ...row, index };
      });
    },
    // 子表单新增
    handleDetailAdd() {
      //添加数据，并禁用表单
      this.tempDetailList.forEach((item) => {
        if (
          !this.form.buyBackOrderDetailList.some(
            (order) => order.id === item.id
          )
        ) {
          this.form.buyBackOrderDetailList.push({ ...item });
        }
        this.setRowDisabled(item.index, true);
      });
      this.clearSelection("reqTable");
    },
    // 子表单禁用
    isRowSelectable(row) {
      return !row.disabled;
    },
    // 子表单删除
    handleDetailDelete() {
      this.deleteIds.forEach((id) => {
        const index = this.buyBackReqDetailList.findIndex(
          (item) => item.id === id
        );
        if (index !== -1) this.setRowDisabled(index, false);
      });
      this.form.buyBackOrderDetailList =
        this.form.buyBackOrderDetailList.filter(
          (item) => !this.deleteIds.includes(item.id)
        );
      this.clearSelection("orderTable");
    },
    // 设置行的禁用状态
    setRowDisabled(index, disabled) {
      if (index !== -1) {
        this.$set(this.buyBackReqDetailList[index], "disabled", disabled);
      }
    },
    // 清空选择状态
    clearSelection(ref) {
      this.$refs[ref].clearSelection();
    },

    /**
     * 内部采购退货申请弹窗
     */
    //
    //采购退货申请弹窗
    showBuyBackReq() {
      if (this.$refs["buyBackReqTable"]) {
        this.$refs["buyBackReqTable"].setCurrentRow();
      }
      this.innerVisible = true;
      this.getBuyBackReqList();
    },
    // 关闭内部采购入库单对话框
    cancelInner() {
      this.innerVisible = false;
    },
    /** 查询内部采购入库单列表 */
    getBuyBackReqList() {
      this.buyBackReqLoading = true;
      this.queryBuyBackReqParams.params = {};
      this.queryBuyBackReqParams.supplierId = this.form.supplierId;
      if (
        null != this.daterangeBuyBackReqOrderDate &&
        "" != this.daterangeBuyBackReqOrderDate
      ) {
        this.queryBuyBackReqParams.params["beginOrderDate"] =
          this.daterangeBuyBackReqOrderDate[0];
        this.queryBuyBackReqParams.params["endOrderDate"] =
          this.daterangeBuyBackReqOrderDate[1];
      }
      listBuyBackReq(this.queryBuyBackReqParams).then((response) => {
        this.buyBackReqList = response.rows;
        this.buyBackReqTotal = response.total;
        this.buyBackReqLoading = false;
      });
    },
    /** 内部采购入库单搜索按钮操作 */
    handleBuyBackReqQuery() {
      this.queryBuyBackReqParams.pageNum = 1;
      this.getBuyBackReqList();
    },
    /** 重置按钮操作 */
    resetBuyBackReqQuery() {
      this.daterangeBuyBackReqOrderDate = [];
      this.resetForm("queryBuyBackReqForm");
      this.handleBuyBackReqQuery();
    },
    //内部采购入库单选框选中数据
    handleCurrentChange(val) {
      this.resetDetailList();
      if (val == null) {
        return;
      }
      this.form.buyBackReq = val;
      this.form.srcUserId = val.srcUserId;
      this.form.srcUser = val.srcUser;
      this.form.srcDeptName = val.srcDeptName;
      this.queryBuyBackReqParams.pageNum = 1;
      this.form.buyBackReqId = val.id;
      this.form.supplierId = val.supplierId;
      getBuyBackReqDetailListByBuyBackReqId(val.id).then((response) => {
        this.buyBackReqDetailList = response.data;
      });
      //供应商id
      this.innerVisible = false;
    },
    // 重置详情列表yi
    resetDetailList() {
      this.form.buyBackOrderDetailList = [];
      this.buyBackReqDetailList = [];
      this.tempDetailList = [];
      this.form.buyBackReqId = null;
      this.form.buyBackReqCode = null;
      this.form.srcDeptName = null;
      this.form.srcUser = { userName: null };
      this.form.buyBackReq = {
        code: "",
      };
    },
    // 采购退货单详情仓库改变
    handleHouseChange(row) {
      const queryHouse = {
        goodsId: row.goodsId,
        houseId: row.houseId,
      };
      const index = this.form.buyBackOrderDetailList.findIndex(
        (item) => item.id === row.id
      );
      getStockByGoodsIdHouseId(queryHouse).then((rs) => {
        this.$set(this.form.buyBackOrderDetailList[index], "stock", rs.data);
        this.$set(this.form.buyBackOrderDetailList[index], "costAll", 0);
        this.$set(this.form.buyBackOrderDetailList[index], "outStock", null);
      });
    },
    // 动态表单校验规则
    validateStock(row) {
      if (row.houseId == null) {
        this.$message.error("仓库不能为空");
        row.outStock = null;
        return;
      }

      // 检查是否为数字且非空
      let outStock = parseFloat(row.outStock);
      const isValidNumber = /^[1-9]\d*$/.test(row.outStock);

      if (!isValidNumber || isNaN(outStock)) {
        this.$message.error("请输入有效的正数");
        row.outStock = null;
        return;
      }

      // 校验退货数量不能小于0
      if (outStock < 0) {
        this.$message.error("退货数量不能小于0");
        row.outStock = null;
        return;
      }

      const minValue = Math.min(row.stock, row.quantity);

      // 校验退货数量不能超过入库数量
      if (outStock > minValue) {
        this.$message.error(`退货数量不能超过${minValue}`);
        row.outStock = row.minValue;
      }
      this.calculateCostAll(row); // 更新结算金额
    },
    // 计算结算金额
    calculateCostAll(row) {
      this.form.buyBackOrderDetailList.forEach((item) => {
        if (item.goodsId === row.goodsId) {
          item.costAll = (row.cost * row.outStock).toFixed(2); // 计算并保留两位小数
        }
      });
    },
    //校验表单
    checkForm() {
      if (
        !Array.prototype.isPrototypeOf(this.form.buyBackOrderDetailList) ||
        this.form.buyBackOrderDetailList.length === 0
      ) {
        this.$message.error("采购退货详情不能为空");
        return false;
      }
      this.form.buyBackOrderDetailList.forEach((item) => {
        if (item.outStock == null) {
          this.$message.error("退货数量不能为空");
          return false;
        }
      });
      return true;
    },
    // 显示表单详细信息
    showFormDetail() {
      this.formDetailDisabled = !this.formDetailDisabled;
    },
  },
};
</script>
<style scoped>
/**  长度过长的文本省略号 */
.ellipsis-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 120px;
}
</style>
